import { IN_ELECTRON } from "@follow/shared/constants"
import { env } from "@follow/shared/env.desktop"
import { setFirebaseTracker, setPostHogTracker, tracker } from "@follow/tracker"
import type { AuthSessionResponse } from "@follow-app/client-sdk"
import PKG from "@pkg"
import posthog from "posthog-js"

import { QUERY_PERSIST_KEY } from "~/constants/app"

import { ga4 } from "../lib/ga4"

export const initAnalytics = async () => {
  tracker.manager.appendUserProperties({
    build: IN_ELECTRON ? "electron" : "web",
    version: PKG.version,
    // 根据错误信息，PKG 对象上不存在 gitCommit 属性，这里假设使用 mainHash 替代
    hash: PKG.mainHash,
    language: navigator.language,
  })

  try {
    setFirebaseTracker(ga4)
  } catch (error) {
    console.warn("Failed to set Firebase tracker:", error)
  }

  if (env.VITE_POSTHOG_KEY && env.VITE_POSTHOG_HOST) {
    try {
      setPostHogTracker(
        posthog.init(env.VITE_POSTHOG_KEY, {
          api_host: env.VITE_POSTHOG_HOST,
          person_profiles: "identified_only",
          defaults: "2025-05-24",
        }),
      )
    } catch (error) {
      console.warn("Failed to initialize PostHog:", error)
    }
  }

  try {
    let session: AuthSessionResponse | undefined
    try {
      const queryData = JSON.parse(window.localStorage.getItem(QUERY_PERSIST_KEY) ?? "{}")
      session = queryData.clientState.queries.find(
        (query: any) => query.queryHash === JSON.stringify(["auth", "session"]),
      )?.state.data.data
    } catch {
      // do nothing
    }
    if (session?.user) {
      tracker.identify(session.user)
    }
  } catch (error) {
    console.warn("Failed to identify user:", error)
  }
}
